package com.mofum.msdom.excel.constant;

import com.mofum.msdom.excel.template.event.TemplateCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yuyang@qxy37.com
 * @since 2019/2/1 0001 16:41
 */
public class TemplateConfig {

    public static final String DEFAULT_REG = "\\$\\{([\\s\\S]*?)\\}\\$";

    public static final String EXTRACT_REG = "\\$\\{|\\}\\$";

    public static final TemplateConfig DEFAULT_CONFIG = new TemplateConfig(DEFAULT_REG, EXTRACT_REG);

    /**
     * 模板项表达式
     */
    private String itemReg;

    /**
     * 提取值表达式
     */
    private String extractReg;

    /**
     * 值回调
     */
    private TemplateCallback valueCallback;

    /**
     * 属性回调
     */
    private TemplateCallback propCallback;

    public static String replaceName(String itemReg, String value) {
        return value.replaceAll(itemReg, "").trim();
    }

    public static String replaceReg(String itemReg, String value) {
        return value.replaceAll(itemReg, "#").trim();
    }

    public static String replaceSingleProp(String prop, String value,String replacement) {
        return value.replaceAll("#(\\s*" + prop + "\\s*)#", replacement).trim();
    }

    public static boolean isHasItemRegExpressions(String itemReg, String value) {
        List<String> codes = TemplateConfig.getMatcher(itemReg, value);
        if (codes == null && codes.size() == 0) {
            return false;
        }
        return true;
    }

    public static List<String> getMatcher(String regex, String source) {
        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            result.add(matcher.group());
        }
        return result;
    }

    public TemplateConfig() {
    }

    public TemplateConfig(String itemReg, String extractReg) {
        this.itemReg = itemReg;
        this.extractReg = extractReg;
    }

    public String getItemReg() {
        return itemReg;
    }

    public void setItemReg(String itemReg) {
        this.itemReg = itemReg;
    }

    public String getExtractReg() {
        return extractReg;
    }

    public void setExtractReg(String extractReg) {
        this.extractReg = extractReg;
    }

    public TemplateCallback getValueCallback() {
        if(valueCallback == null){
            valueCallback = TemplateCallback.DEFAULT;
        }
        return valueCallback;
    }

    public void setValueCallback(TemplateCallback valueCallback) {
        this.valueCallback = valueCallback;
    }

    public TemplateCallback getPropCallback() {
        if(propCallback == null){
            propCallback = TemplateCallback.DEFAULT;
        }
        return propCallback;
    }

    public void setPropCallback(TemplateCallback propCallback) {
        this.propCallback = propCallback;
    }
}
